package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/*
    Mapper工具类
 */
public class MapperUtils {

    private InputStream is = null;
    private SqlSession sqlSession = null;


    public MapperUtils() {
    }

    /**
     * 获取SqlSession
     *
     * @param resource resource路径中的配置文件名
     * @return 获取到的SqlSession对象
     */
    public SqlSession getSqlSession(String resource) {

        try {
            //读取核心配置文件
            is = Resources.getResourceAsStream(resource);
            //获取sqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //获取sqlSession 自动提交事务
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sqlSession;
    }

    /**
     * 释放资源
     */
    public void closeResource() {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (sqlSession != null) {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
